package database

import (
	"database/sql"
	"github.com/mix-go/dotenv"
	"gorm.io/driver/mysql"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	_ "mytest/dotenv"
	"time"
)

var (
	DB    *gorm.DB
	SqlDB *sql.DB
)

func init() {
	dbType := dotenv.Getenv("DB_TYPE").Int64()
	var dialector gorm.Dialector
	if dbType == 1 {
		dsn := dotenv.Getenv("DATABASE_PATH").String()
		dialector = sqlite.Open(dsn)
	} else {
		dsn := dotenv.Getenv("DATABASE_DSN").String()
		dialector = mysql.Open(dsn)
	}
	ormConf := &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   dotenv.Getenv("TABLE_PREFIX").String(), //表前缀
			SingularTable: true,                                   //表名是否复数,true=单数
		},
		NowFunc: func() time.Time {
			return time.Now().Local()
		},
		Logger: logger.Default, //日志是否输出sql,默认是不输出
	}
	if dotenv.Getenv("SQL_LOG").Bool() { //根据配置控制是否输出sql
		ormConf.Logger = logger.Default.LogMode(logger.Info)
	}
	db, err := gorm.Open(dialector, ormConf)
	if err != nil {
		log.Fatalf("初始化mysql失败,err: %s \n", err)
	}

	sqlDB, err := db.DB()
	if err != nil {
		log.Fatalf("初始化mysql DB 失败,err: %s \n", err)
	}
	sqlDB.SetMaxIdleConns(int(dotenv.Getenv("MAX_IDLE_CONNS").Int64()))
	sqlDB.SetMaxOpenConns(int(dotenv.Getenv("MAX_OPEN_CONNS").Int64()))
	sqlDB.SetConnMaxLifetime(time.Duration(dotenv.Getenv("MAX_OPEN_CONNS").Int64()) * time.Second)

	DB = db
	SqlDB = sqlDB
}
